package com.vcc.boss.core.queue.batch.unFreeze.queue;

import com.vcc.boss.core.queue.batch.unFreeze.model.UnFreezeQueueDto;
import com.vcc.channel.base.model.response.CardInfoVo;
import com.vcc.channel.base.service.ChannelBaseService;
import com.vcc.core.util.IdWorker;
import com.vcc.data.entity.UserCard;
import com.vcc.service.service.TaskLogService;
import com.vcc.service.service.UserCardService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;

@Component
public class UnFreezeQueue implements CommandLineRunner {

    @Autowired
    private UserCardService userCardService;
    @Autowired
    private TaskLogService taskLogService;
    @Resource
    private ApplicationContext applicationContext;

    private static final Logger logger = LoggerFactory.getLogger(UnFreezeQueue.class);

    private volatile DelayQueue<UnFreezeQueueDto> delayQueue = new DelayQueue<UnFreezeQueueDto>();


    public void add(String orderId, String cardNumber, Integer index, Integer targetIndex) {
        synchronized (this) {
            UnFreezeQueueDto unFreezeQueueDto = delayQueue.stream().filter(it -> it.getCardNumber().equals(cardNumber) && it.getOrderId().equals(orderId)).findFirst().orElse(null);
            if (unFreezeQueueDto == null) {
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime nowB = now.plusSeconds(5L);
                long betweenMillis = ChronoUnit.MILLIS.between(now, nowB);
                logger.info("当前添加的是${orderId},秒${time}");
                delayQueue.put(
                        new UnFreezeQueueDto(
                                orderId, System.currentTimeMillis() + betweenMillis, cardNumber, index, targetIndex
                        )
                );
            }
        }
    }


    @Override
    public void run(String... args) throws Exception {
        Executors.newSingleThreadExecutor().execute(new Thread(this::excuteThread));
    }

    private void excuteThread() {
        while (true) {
            try {
                processTask(delayQueue.take());
            } catch (InterruptedException e) {
                break;
            }
        }
    }

    /**
     * 内部执行延时任务
     *
     * @param unFreezeQueueDto
     */
    private void processTask(UnFreezeQueueDto unFreezeQueueDto) {
        try {
            logger.info("当前处理的卡是{}", unFreezeQueueDto.getCardNumber());
            UserCard userCard = userCardService.getByCardNumber(unFreezeQueueDto.getCardNumber());
            ChannelBaseService channelBaseService = applicationContext.getBean(userCard.getChannelCode(), ChannelBaseService.class);
            CardInfoVo cardInfo = channelBaseService.queryCardInfo(userCard.getChannelCardId());
            if ("REVOKED".equals(cardInfo.getCardStatus())) {
                channelBaseService.unblockCard(userCard.getChannelCardId(), IdWorker.getStringOrderId());
            }
            taskLogService.processedSuccess(unFreezeQueueDto.getOrderId());
        } catch (Exception e) {
            taskLogService.processedError(unFreezeQueueDto.getOrderId());
            logger.error("异常", e);
        } finally {
            if (unFreezeQueueDto.getIndex().equals(unFreezeQueueDto.getTargetIndex())) {
                taskLogService.processedAccomplish(unFreezeQueueDto.getOrderId());
            }
        }
    }
}
